
function addLoadEvent(func){
    let onload = window.onload
    if(typeof window.onload != 'function'){
        window.onload = func
    }else{
        window.onload = function(){
            onload()
            func()
        }
    }
}

function insertAfter(newElement,targetElement){
    let parent = targetElement.parentNode
    if(parent.lastChild == targetElement){
        parent.appendChild(newElement)
    }else{
        parent.insertBefore(newElement,targetElement.nextSibling)   //插入到目标节点的下一个兄弟节点之前
    }
}

function preparePlaceholder(){
    let placeholder = document.createElement('img')
    placeholder.setAttribute('id','placeholder')
    placeholder.setAttribute('src','./image/Color/2019.jfif')
    placeholder.setAttribute('alt','Maybe everybody is unhappy!')
    let createP = document.createElement('p')
    createP.setAttribute('id','createP')
    let createText = document.createTextNode('You are right! ^ v ^')
    createP.appendChild(createText)
    let gallry = document.getElementById('imagegallery')
    insertAfter(placeholder,gallry)
    insertAfter(createP,placeholder)
}

function prepareGallery(){
    let gallery = document.getElementById('imagegallery')
    let links = gallery.getElementsByTagName('a')
    for(let i=0;i<links.length;i++){
        links[i].onclick = function(){
            return showPic(this)
        }
        links[i].onkeypress = links[i].onclick
    }
}

function showPic(whichPic){
    let source = whichPic.getAttribute('href')
    let placeholder = document.getElementById('placeholder')
    placeholder.setAttribute('src',source)
    if(whichPic.getAttribute('title')){
        var text = whichPic.getAttribute('title')
    }else{
        var text = ''
    }
    let createP = document.getElementById('createP')
    if(createP.firstChild.nodeType == 3){
        createP.firstChild.nodeValue = text
    }
    return false
}

addLoadEvent(preparePlaceholder)
addLoadEvent(prepareGallery)